﻿package bakudo.utils.massPopulator 
{
	import flash.utils.clearTimeout;
	import flash.utils.getDefinitionByName;
	import flash.utils.setTimeout;
	/**
	 * ...
	 * @author Bakudo
	 */
	public class MassPopulator
	{
		//::::::::::::::: public vars ::::::::::::::://
		/**
		 * Function invoked on every loop pass
		 * We can connect our own function and handle item creation
		 */
		public var createItemHandler : Function;
		/**
		 * When all items are created, this function is executed
		 * We can connect our own function and handle this event
		 */
		public var allItemsPopulatedHandler : Function;
		/**
		 * Amount of item which are needed to be created
		 */
		public var amount : uint;
		/**
		 * Max number of items created in one loop pass
		 * After this we use short timeout to not to choke FlashPlayer
		 */
		public var maxLoopItems : uint;
		
		//::::::::::::::: private vars :::::::::::::://
		private var k : uint;
		private var maxLoops : uint;
		private var loopTimeout : uint;
		private var currentLoop : uint;
		
		/**
		 * It starts items population
		 * Method creates an amount number of items of itemClassName class
		 * @param	itemClassName - name of the class used for item creation
		 * @param	amount - amount of items needed to be created
		 * @param	initObject - it will has use in future
		 */
		public function populate(itemClassName : String,amount : uint,initObject:Object=null):void {
			var ClassName : Class = getDefinitionByName(itemClassName) as Class;
			currentLoop = 0;
			maxLoops = Math.floor(amount / maxLoopItems);
			if(amount <= maxLoopItems) {
				maxLoops = 1;
				maxLoopItems = amount;
			}
			doLoop(0, maxLoopItems);
		}
		
		//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
		// PRIVATE METHODS
		//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
		
		private function doNextLoop ():void {
				currentLoop++;
				if (currentLoop < maxLoops) 
				{
					doLoop(k, k + maxLoopItems);
				}
				else if (currentLoop == maxLoops) 
				{
					if (amount % maxLoopItems == 0) 
					{
						doFinishLoop();
					}
					else 
					{ 
							//tworzenie ogona n elementow z podzialu
							trace('tworz ogon bo ',(amount % maxLoopItems));
							doLoop(k, k + amount % maxLoopItems);
					}
				} 
				else 
					{
						doFinishLoop();
					}
				};
		
		private function doLoop(start:uint,end:uint):void {
				k = start;
				trace('start : ', k, 'end', end);
				while(k < end) {
					createItemHandler(k);		
					k++;
				}
				clearTimeout(loopTimeout);
				loopTimeout = setTimeout(doNextLoop, 2);
			};
			
			
			private function doFinishLoop ():void {
				allItemsPopulatedHandler();
				
			}
		
	}

}